package com.foolishbird.sdk.utils;

import android.os.Build;
import android.os.SystemProperties;
import android.text.TextUtils;


import com.foolishbird.sdk.BuildConfig;

import java.util.Arrays;

public final class AndroidEmulatorChecker {

    public static final String UNKNOWN = "unknown";

    private AndroidEmulatorChecker() {
    }

    public static boolean isAndroidEmulator() {
        if(BuildConfig.DEBUG){
            return false;
        }

        return isX86Cpu() || isSupportedNativeBridge() || isSupportX86CpuAbi();
    }

    /**
     * 检查Android设备是否支持在x86系统上是否能够运行ARM架构的软件，即arm指令集转x86指令集
     *
     * @return
     */
    public static boolean isSupportedNativeBridge() {
        return TextUtils.equals("libnb.so", getString("ro.dalvik.vm.native.bridge"));
    }

    /**
     * 检查Android设备是否支持x86指令集
     *
     * @return
     */
    private static boolean isX86Cpu() {
        return TextUtils.equals("x86", getString("ro.dalvik.vm.isa.arm"));
    }

    /**
     * 检查Android设备是否支持x86软件运行
     *
     * @return
     */
    private static boolean isSupportX86CpuAbi() {
        if (Build.VERSION.SDK_INT < 21) {
            return TextUtils.equals("x86", getString("ro.product.cpu.abi"))
                    || Build.CPU_ABI.equalsIgnoreCase("x86")
                    || TextUtils.equals("x86", getString("ro.product.cpu.abi2"))
                    || Build.CPU_ABI2.equalsIgnoreCase("x86");
        } else {
            return binarySearch(getStringList("ro.product.cpu.abilist", ","), "x86")
                    || binarySearch(Build.SUPPORTED_ABIS, "x86")
                    || binarySearch(getStringList("ro.product.cpu.abilist32", ","), "x86")
                    || binarySearch(getStringList("ro.product.cpu.abilist64", ","), "x86");

        }
    }

    public static String getString(String property) {
        return SystemProperties.get(property, UNKNOWN);
    }

    public static String[] getStringList(String property, String separator) {
        String value = SystemProperties.get(property);
        if (value.isEmpty()) {
            return new String[0];
        } else {
            return value.split(separator);
        }
    }

    private static boolean binarySearch(String[] array, String keyword) {
        Arrays.sort(array);
        return Arrays.binarySearch(array, keyword) > 0;
    }
}
